package com.coursebooking.service;

import com.coursebooking.model.User;
import com.coursebooking.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private StudentService studentService;
    
    @Autowired
    private TeacherService teacherService;

    public User createUser(String username, String password, String email, User.Role role, Long relatedId) {
        if (userRepository.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }
        if (userRepository.existsByEmail(email)) {
            throw new RuntimeException("邮箱已存在");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setEmail(email);
        user.setRole(role);
        user.setRelatedId(relatedId);
        user.setIsActive(true);

        userRepository.insert(user);
        return user;
    }

    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public User findByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    public User findById(Long id) {
        return userRepository.selectById(id);
    }

    public List<User> findAll() {
        return userRepository.selectList(null);
    }

    public User updateUser(User user) {
        userRepository.updateById(user);
        return user;
    }

    public void deleteUser(Long id) {
        User user = userRepository.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 根据用户角色删除关联的学生或教师记录
        if (user.getRole() == User.Role.STUDENT && user.getRelatedId() != null) {
            if (studentService.existsById(user.getRelatedId())) {
                studentService.deleteStudent(user.getRelatedId());
            }
        } else if (user.getRole() == User.Role.TEACHER && user.getRelatedId() != null) {
            if (teacherService.existsById(user.getRelatedId())) {
                teacherService.deleteTeacher(user.getRelatedId());
            }
        }
        
        userRepository.deleteById(id);
    }

    public boolean existsByUsername(String username) {
        return userRepository.existsByUsername(username);
    }

    public boolean existsByEmail(String email) {
        return userRepository.existsByEmail(email);
    }

    public void updateLastLogin(String username) {
        User user = userRepository.selectByUsername(username);
        if (user != null) {
            user.setLastLogin(LocalDateTime.now());
            userRepository.updateById(user);
        }
    }

    public boolean validatePassword(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    public void changePassword(Long userId, String newPassword, String oldPassword) {
        User user = userRepository.selectById(userId);
        if (!validatePassword(oldPassword, user.getPassword())) {
            throw new RuntimeException("旧密码错误");
        }
        if (user != null) {
            user.setPassword(passwordEncoder.encode(newPassword));
            userRepository.updateById(user);
        } else {
            throw new RuntimeException("用户不存在");
        }
    }
}